#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import pycurl
import StringIO
import sys
import json
import datetime

NOW = datetime.datetime.now()
THREE_DAYS_AGO = NOW - datetime.timedelta(days=3)

DATE_START = THREE_DAYS_AGO.strftime("%Y/%m/%d")
DATE_END = NOW.strftime("%Y/%m/%d")
NOW_DATE = NOW.strftime("%Y%m%d")


def Get_PMCID_List():
    try:
        url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi'
        buf = StringIO.StringIO()
        c = pycurl.Curl()
        c.setopt(pycurl.POST, 1)
        c.setopt(c.URL, url)
        c.setopt(pycurl.HTTPPOST, [('db', 'pmc'), ('mindate', DATE_START), ('maxdate', DATE_END), ('retmode', "json"),
                                   ('retmax', "100000")])
        c.setopt(c.WRITEFUNCTION, buf.write)
        c.perform()
        result = buf.getvalue()
        json.loads(result)
        outfile = open("pmcid_list_" + NOW_DATE + ".json", "w")
        outfile.write(buf.getvalue())
        outfile.close()
        buf.close()
        print "pmcid_list_" + NOW_DATE + " has been successfully downloaded."
    except ValueError:
        Get_PMCID_List()


if __name__ == '__main__':
    if len(sys.argv) >= 3:
        DATE_START = sys.argv[1]
        DATE_END = sys.argv[2]
    Get_PMCID_List()
